package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.feign.UserFeign;
import com.changgou.pojo.User;
import com.changgou.web.CasUtil;
import com.fasterxml.jackson.annotation.JsonAlias;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Project: com.changgou.controller
 * @Author: ShaoDi Wang
 * @Date: Created in 2019-08-13 09:20
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("/setting")
public class SettingController {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 解绑手机号码专用接口
     * @param mobileMap {
     *     "verifyCode"(验证码)
     *     "mobileNumber"(新手机号码)
     * }
     * @return
     */
    @PostMapping("/safe/mobile/sendsms")
    public Result sendSms(@RequestBody Map<String,String> mobileMap) {

        // 远程调用user微服务，查询用户信息
        String userName = CasUtil.loginName();
        Result userResult = userFeign.findById(userName);
        User user = JSON.parseObject( JSON.toJSONString( userResult.getData() ),
                User.class );
        String verifyCode = mobileMap.get("verifyCode");
        String tempVcode = (String)redisTemplate.boundValueOps("verifyCode_" + userName + user.getPhone()).get();
        if(verifyCode == null || tempVcode == null){
            return new Result(false,StatusCode.ERROR,"验证码错误");
        }
        if(!verifyCode.equalsIgnoreCase(tempVcode)){
            return new Result(false, StatusCode.ERROR, "验证码输入不正确");
        }
        // 传了新手机用新手机号码，否则用旧手机号码
        String mobilePhone = user.getPhone();
        if(mobileMap.get("mobileNumber") != null){
            Map<String,String> searchMap = new HashMap<>(1);
            searchMap.put("phone",mobileMap.get("mobileNumber"));
            Result list = userFeign.findList(searchMap);
            List<User> users = JSON.parseArray(JSON.toJSONString(list.getData()),
                    User.class);
            if(users.size() > 0){
                return new Result(false, StatusCode.ERROR, "该手机号已被使用");
            }
            mobilePhone = mobileMap.get("mobileNumber");
        }
        userFeign.sendSms(mobilePhone);
        return new Result(true, StatusCode.OK, "短信发送成功");
    }

    /**
     * 换绑手机号码第二步接口(绑定新手机号)
     * @param mobileMap
     * @return
     */
    @PostMapping("/safe/mobile/second")
    public Result mobileSecond(@RequestBody Map<String,String> mobileMap){
        // 远程调用user微服务，查询用户信息
        String userName = CasUtil.loginName();
        Result userResult = userFeign.findById(userName);
        User user = JSON.parseObject( JSON.toJSONString( userResult.getData() ),
                User.class );
        String verifyCode = mobileMap.get("verifyCode");
        String tempVcode = (String)redisTemplate.boundValueOps("verifyCode_" + userName + user.getPhone()).get();
        if(verifyCode == null || tempVcode == null){
            return new Result(false,StatusCode.ERROR,"验证码错误");
        }
        if(!verifyCode.equalsIgnoreCase(tempVcode)){
            return new Result(false, StatusCode.ERROR, "验证码输入不正确");
        }
        String smsCode = mobileMap.get("smsCode");
        String tempSmsCode =
                (String) redisTemplate.boundValueOps("code_" + mobileMap.get("mobileNumber")).get();
        if(smsCode == null || tempSmsCode == null){
            return new Result(false,StatusCode.ERROR, "短信验证码错误");
        }
        if(!smsCode.equalsIgnoreCase(tempSmsCode)){
            return new Result(false,StatusCode.ERROR,"短信验证码输入错误");
        }
        user.setPhone(mobileMap.get("mobileNumber"));
        userFeign.update(user,userName);
        return new Result(true, StatusCode.OK, "成功绑定新手机号");
    }

    /**
     * 换绑手机号码第一步接口(验证身份)
     * @param mobileMap
     * @return
     */
    @PostMapping("/safe/mobile/first")
    public Result mobileFirst(@RequestBody Map<String,String> mobileMap){
        // 远程调用user微服务，查询用户信息
        String userName = CasUtil.loginName();
        Result userResult = userFeign.findById(userName);
        User user = JSON.parseObject( JSON.toJSONString( userResult.getData() ),
                User.class );
        String verifyCode = mobileMap.get("verifyCode");
        String tempVcode = (String)redisTemplate.boundValueOps("verifyCode_" + userName + user.getPhone()).get();
        if(verifyCode == null || tempVcode == null){
            return new Result(false,StatusCode.ERROR,"验证码错误");
        }
        if(!verifyCode.equalsIgnoreCase(tempVcode)){
            return new Result(false, StatusCode.ERROR, "验证码输入不正确");
        }
        String smsCode = mobileMap.get("smsCode");
        String tempSmsCode = (String) redisTemplate.boundValueOps("code_" + user.getPhone()).get();
        if(smsCode == null || tempSmsCode == null){
            return new Result(false,StatusCode.ERROR, "短信验证码错误");
        }
        if(!smsCode.equalsIgnoreCase(tempSmsCode)){
            return new Result(false,StatusCode.ERROR,"短信验证码输入错误");
        }
        return new Result(true,StatusCode.OK,"");
    }

    /**
     * 换密码接口
     * @param pwdMap
     * @return
     */
    @PostMapping("/safe/pwd")
    public Result updatePwd(@RequestBody Map<String,String> pwdMap){
        // 远程调用user微服务，查询用户信息
        Result userResult = userFeign.findById(CasUtil.loginName());
        User user = JSON.parseObject( JSON.toJSONString( userResult.getData() ),
                User.class );
        // 校验旧密码
        if(!passwordEncoder.matches(pwdMap.get("oldPassword"), user.getPassword())){
            return new Result(false, StatusCode.ERROR,"旧密码输入错误");
        }
        if(pwdMap.get("password")!=null && pwdMap.get("confirmPassword")!=null){
            if(!pwdMap.get("password").equals(pwdMap.get("confirmPassword"))){
                return new Result( false, StatusCode.ERROR, "新密码两次输入不一致");
            }
        }
        user.setPassword(passwordEncoder.encode(pwdMap.get("password")));
        userFeign.update(user,CasUtil.loginName());
        return new Result(true, StatusCode.OK,"");
    }
}
